
// ************************************
// * GStore - Inventory System - thomasfn *
// ************************************
// SHARED

ITEM.Classname = "base_container"
ITEM.Printname = "Base Container"

ITEM.Description = "All GStore containers derive from this item!"

ITEM.MassLimit = 5
ITEM.ItemLimit = 5

ITEM.IsContainer = true

ITEM.ContainerBase = ITEM

function ITEM:Init( id )
	self.RootBase.Init( self, id )
	self.Items = {}
	self.CurrentMass = 0
	if (CLIENT) then self.Waiting = {} end
end

function ITEM:GetMass()
	return self.RootBase.GetMass( self ) + self.CurrentMass
end

function ITEM:IsEmpty()
	return #self.Items == 0
end

if (SERVER) then

	function ITEM:MakeEmpty()
		local i
		for i=1, #self.Items do
			self.Items[ i ]:ToWorld( self:RandomPos( self:GetPos(), 32 ) )
		end
		self.Items = {}
		self.CurrentMass = 0
		self:UpdateNeeded()
	end
	
	function ITEM:CanHoldItem( item )
		if (item:GetMass() > (self.MassLimit-self:GetMass())) then return false end
		if (#self.Items >= self.ItemLimit) then return false end
		if (item.IsContainer && (!item:IsEmpty())) then return false end
		return true
	end
	
	function ITEM:AddItem( item )
		table.insert( self.Items, item )
		self.CurrentMass = self.CurrentMass + item:GetMass()
		item:FromWorld( self )
		self:UpdateNeeded()
	end
	
	function ITEM:RemoveItem( item )
		for id, it in pairs( self.Items ) do
			if (item == it) then
				table.remove( self.Items, id )
				break
			end
		end
		self.CurrentMass = self.CurrentMass - item:GetMass()
		item.Container = nil
		item:ToWorld( self:GetPos() )
		self:UpdateNeeded()
	end
	
	function ITEM:HasItem( item )
		return table.HasValue( self.Items, item )
	end
	
	function ITEM:Manifest()
		umsg.Char( #self.Items )
		local i
		for i=1, #self.Items do
			umsg.Short( self.Items[ i ]._id )
		end
	end

end

if (CLIENT) then

	function ITEM:Update( um )
		local itms = um:ReadChar()
		local i
		self.Items = {}
		self.CurrentMass = 0
		for i=1, itms do
			local id = um:ReadShort()
			local item = gstore.GetItem( id )
			if (item) then
				self.Items[ i ] = item
				self.CurrentMass = self.CurrentMass + item:GetMass()
			else
				// This item isn't synced to us yet but will be very soon
				// We need to wait for it to arrive, then update us
				table.insert( self.Waiting, { i, id } )
			end
		end
	end
	
	function ITEM:ShowUI()
		gstore_ui.CreateContainerWindow( self )
	end
	
	function ITEM:Tick()
		self.RootBase.Tick( self )
		// TODO: Handle waiting queue here
	end

end